#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
组合模式 (Composite Pattern) - Python实现详解

组合模式是一种结构设计模式，它将对象组合成树形结构以表示"部分-整体"的层次结构。
组合模式使得用户对单个对象和组合对象的使用具有一致性。

与Java对比：
1. Python的列表和字典提供了天然的组合结构支持
2. Python的装饰器可以实现动态组合
3. Python的生成器支持惰性组合遍历
4. Python的上下文管理器支持组合资源管理

作者: Assistant
日期: 2024
"""

import time
import threading
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Callable, Union, Iterator
from dataclasses import dataclass, field
from enum import Enum
import json
import uuid
from collections import defaultdict
import weakref


# ============================================================================
# 1. 传统组合模式实现
# ============================================================================

class Component(ABC):
    """
    组件抽象类
    定义了叶子和组合对象的共同接口
    """
    
    def __init__(self, name: str):
        self._name = name
        self._parent: Optional['Component'] = None
    
    @property
    def name(self) -> str:
        """获取组件名称"""
        return self._name
    
    @property
    def parent(self) -> Optional['Component']:
        """获取父组件"""
        return self._parent
    
    def set_parent(self, parent: Optional['Component']) -> None:
        """设置父组件"""
        self._parent = parent
    
    @abstractmethod
    def operation(self) -> str:
        """执行操作"""
        pass
    
    @abstractmethod
    def get_size(self) -> int:
        """获取大小"""
        pass
    
    def is_composite(self) -> bool:
        """判断是否为组合对象"""
        return False
    
    def add(self, component: 'Component') -> None:
        """添加子组件（叶子节点不支持）"""
        raise NotImplementedError("Leaf components cannot add children")
    
    def remove(self, component: 'Component') -> None:
        """移除子组件（叶子节点不支持）"""
        raise NotImplementedError("Leaf components cannot remove children")
    
    def get_child(self, index: int) -> 'Component':
        """获取子组件（叶子节点不支持）"""
        raise NotImplementedError("Leaf components have no children")
    
    def get_path(self) -> str:
        """获取组件路径"""
        if self._parent is None:
            return self._name
        return f"{self._parent.get_path()}/{self._name}"


class Leaf(Component):
    """
    叶子组件
    表示组合中的叶子对象，叶子对象没有子对象
    """
    
    def __init__(self, name: str, size: int = 1):
        super().__init__(name)
        self._size = size
    
    def operation(self) -> str:
        """执行叶子操作"""
        return f"Leaf({self._name}): Performing operation"
    
    def get_size(self) -> int:
        """获取叶子大小"""
        return self._size
    
    def set_size(self, size: int) -> None:
        """设置叶子大小"""
        self._size = size
    
    def __str__(self) -> str:
        return f"Leaf({self._name}, size={self._size})"


class Composite(Component):
    """
    组合组件
    表示有子组件的组件，实现了子组件相关的操作
    """
    
    def __init__(self, name: str):
        super().__init__(name)
        self._children: List[Component] = []
    
    def operation(self) -> str:
        """执行组合操作"""
        results = [f"Composite({self._name}): Performing operation"]
        
        for child in self._children:
            child_result = child.operation()
            # 为子组件结果添加缩进
            indented_result = "  " + child_result.replace("\n", "\n  ")
            results.append(indented_result)
        
        return "\n".join(results)
    
    def get_size(self) -> int:
        """获取组合大小（所有子组件大小之和）"""
        return sum(child.get_size() for child in self._children)
    
    def is_composite(self) -> bool:
        """判断是否为组合对象"""
        return True
    
    def add(self, component: Component) -> None:
        """添加子组件"""
        self._children.append(component)
        component.set_parent(self)
        print(f"Added {component.name} to {self._name}")
    
    def remove(self, component: Component) -> None:
        """移除子组件"""
        if component in self._children:
            self._children.remove(component)
            component.set_parent(None)
            print(f"Removed {component.name} from {self._name}")
    
    def get_child(self, index: int) -> Component:
        """获取子组件"""
        if 0 <= index < len(self._children):
            return self._children[index]
        raise IndexError(f"Child index {index} out of range")
    
    def get_children(self) -> List[Component]:
        """获取所有子组件"""
        return self._children.copy()
    
    def get_child_count(self) -> int:
        """获取子组件数量"""
        return len(self._children)
    
    def clear(self) -> None:
        """清空所有子组件"""
        for child in self._children:
            child.set_parent(None)
        self._children.clear()
        print(f"Cleared all children from {self._name}")
    
    def find_child(self, name: str) -> Optional[Component]:
        """根据名称查找子组件"""
        for child in self._children:
            if child.name == name:
                return child
        return None
    
    def __str__(self) -> str:
        return f"Composite({self._name}, children={len(self._children)})"
    
    def __iter__(self) -> Iterator[Component]:
        """支持迭代"""
        return iter(self._children)


# ============================================================================
# 2. 文件系统组合模式
# ============================================================================

class FileSystemItem(ABC):
    """
    文件系统项抽象类
    """
    
    def __init__(self, name: str, created_time: float = None):
        self._name = name
        self._created_time = created_time or time.time()
        self._modified_time = self._created_time
        self._parent: Optional['Directory'] = None
    
    @property
    def name(self) -> str:
        return self._name
    
    @property
    def created_time(self) -> float:
        return self._created_time
    
    @property
    def modified_time(self) -> float:
        return self._modified_time
    
    @property
    def parent(self) -> Optional['Directory']:
        return self._parent
    
    def set_parent(self, parent: Optional['Directory']) -> None:
        self._parent = parent
    
    def touch(self) -> None:
        """更新修改时间"""
        self._modified_time = time.time()
    
    @abstractmethod
    def get_size(self) -> int:
        """获取大小（字节）"""
        pass
    
    @abstractmethod
    def get_type(self) -> str:
        """获取类型"""
        pass
    
    def get_path(self) -> str:
        """获取完整路径"""
        if self._parent is None:
            return self._name
        return f"{self._parent.get_path()}/{self._name}"
    
    def get_info(self) -> Dict[str, Any]:
        """获取文件信息"""
        return {
            "name": self._name,
            "type": self.get_type(),
            "size": self.get_size(),
            "path": self.get_path(),
            "created": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self._created_time)),
            "modified": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self._modified_time))
        }


class File(FileSystemItem):
    """
    文件类（叶子节点）
    """
    
    def __init__(self, name: str, content: str = "", created_time: float = None):
        super().__init__(name, created_time)
        self._content = content
        self._extension = name.split('.')[-1] if '.' in name else ""
    
    @property
    def content(self) -> str:
        return self._content
    
    @property
    def extension(self) -> str:
        return self._extension
    
    def write(self, content: str) -> None:
        """写入内容"""
        self._content = content
        self.touch()
        print(f"File {self._name}: Content written ({len(content)} characters)")
    
    def append(self, content: str) -> None:
        """追加内容"""
        self._content += content
        self.touch()
        print(f"File {self._name}: Content appended ({len(content)} characters)")
    
    def read(self) -> str:
        """读取内容"""
        print(f"File {self._name}: Content read ({len(self._content)} characters)")
        return self._content
    
    def get_size(self) -> int:
        """获取文件大小（字符数）"""
        return len(self._content)
    
    def get_type(self) -> str:
        """获取文件类型"""
        return "file"
    
    def get_line_count(self) -> int:
        """获取行数"""
        return len(self._content.split('\n')) if self._content else 0
    
    def __str__(self) -> str:
        return f"File({self._name}, {self.get_size()} bytes)"


class Directory(FileSystemItem):
    """
    目录类（组合节点）
    """
    
    def __init__(self, name: str, created_time: float = None):
        super().__init__(name, created_time)
        self._items: List[FileSystemItem] = []
    
    def add_item(self, item: FileSystemItem) -> None:
        """添加文件系统项"""
        if item.name in [existing.name for existing in self._items]:
            raise ValueError(f"Item '{item.name}' already exists in directory '{self._name}'")
        
        self._items.append(item)
        item.set_parent(self)
        self.touch()
        print(f"Directory {self._name}: Added {item.get_type()} '{item.name}'")
    
    def remove_item(self, item: FileSystemItem) -> None:
        """移除文件系统项"""
        if item in self._items:
            self._items.remove(item)
            item.set_parent(None)
            self.touch()
            print(f"Directory {self._name}: Removed {item.get_type()} '{item.name}'")
    
    def remove_item_by_name(self, name: str) -> bool:
        """根据名称移除文件系统项"""
        item = self.find_item(name)
        if item:
            self.remove_item(item)
            return True
        return False
    
    def find_item(self, name: str) -> Optional[FileSystemItem]:
        """根据名称查找文件系统项"""
        for item in self._items:
            if item.name == name:
                return item
        return None
    
    def get_items(self) -> List[FileSystemItem]:
        """获取所有文件系统项"""
        return self._items.copy()
    
    def get_files(self) -> List[File]:
        """获取所有文件"""
        return [item for item in self._items if isinstance(item, File)]
    
    def get_directories(self) -> List['Directory']:
        """获取所有子目录"""
        return [item for item in self._items if isinstance(item, Directory)]
    
    def get_size(self) -> int:
        """获取目录大小（所有子项大小之和）"""
        return sum(item.get_size() for item in self._items)
    
    def get_type(self) -> str:
        """获取目录类型"""
        return "directory"
    
    def get_item_count(self) -> int:
        """获取项目数量"""
        return len(self._items)
    
    def get_total_file_count(self) -> int:
        """获取总文件数（递归）"""
        count = 0
        for item in self._items:
            if isinstance(item, File):
                count += 1
            elif isinstance(item, Directory):
                count += item.get_total_file_count()
        return count
    
    def list_contents(self, recursive: bool = False, indent: int = 0) -> str:
        """列出目录内容"""
        result = []
        prefix = "  " * indent
        
        for item in sorted(self._items, key=lambda x: (x.get_type(), x.name)):
            if isinstance(item, File):
                result.append(f"{prefix}{item.name} ({item.get_size()} bytes)")
            elif isinstance(item, Directory):
                result.append(f"{prefix}{item.name}/ ({item.get_item_count()} items)")
                if recursive:
                    result.append(item.list_contents(recursive, indent + 1))
        
        return "\n".join(result)
    
    def find_files_by_extension(self, extension: str) -> List[File]:
        """根据扩展名查找文件（递归）"""
        files = []
        for item in self._items:
            if isinstance(item, File) and item.extension == extension:
                files.append(item)
            elif isinstance(item, Directory):
                files.extend(item.find_files_by_extension(extension))
        return files
    
    def create_file(self, name: str, content: str = "") -> File:
        """创建文件"""
        file = File(name, content)
        self.add_item(file)
        return file
    
    def create_directory(self, name: str) -> 'Directory':
        """创建子目录"""
        directory = Directory(name)
        self.add_item(directory)
        return directory
    
    def __str__(self) -> str:
        return f"Directory({self._name}, {len(self._items)} items)"
    
    def __iter__(self) -> Iterator[FileSystemItem]:
        """支持迭代"""
        return iter(self._items)


# ============================================================================
# 3. 组织结构组合模式
# ============================================================================

class Employee(ABC):
    """
    员工抽象类
    """
    
    def __init__(self, name: str, position: str, salary: float):
        self._name = name
        self._position = position
        self._salary = salary
        self._manager: Optional['Manager'] = None
        self._employee_id = str(uuid.uuid4())[:8]
    
    @property
    def name(self) -> str:
        return self._name
    
    @property
    def position(self) -> str:
        return self._position
    
    @property
    def salary(self) -> float:
        return self._salary
    
    @property
    def employee_id(self) -> str:
        return self._employee_id
    
    @property
    def manager(self) -> Optional['Manager']:
        return self._manager
    
    def set_manager(self, manager: Optional['Manager']) -> None:
        self._manager = manager
    
    def set_salary(self, salary: float) -> None:
        """设置薪资"""
        self._salary = salary
        print(f"Employee {self._name}: Salary updated to ${salary:,.2f}")
    
    @abstractmethod
    def get_total_salary(self) -> float:
        """获取总薪资"""
        pass
    
    @abstractmethod
    def get_employee_count(self) -> int:
        """获取员工数量"""
        pass
    
    @abstractmethod
    def work(self) -> str:
        """工作"""
        pass
    
    def get_hierarchy_level(self) -> int:
        """获取层级级别"""
        level = 0
        current = self._manager
        while current is not None:
            level += 1
            current = current.manager
        return level
    
    def get_info(self) -> Dict[str, Any]:
        """获取员工信息"""
        return {
            "id": self._employee_id,
            "name": self._name,
            "position": self._position,
            "salary": self._salary,
            "level": self.get_hierarchy_level(),
            "manager": self._manager.name if self._manager else None
        }
    
    def __str__(self) -> str:
        return f"{self._name} ({self._position})"


class IndividualContributor(Employee):
    """
    个人贡献者（叶子节点）
    """
    
    def __init__(self, name: str, position: str, salary: float, skills: List[str] = None):
        super().__init__(name, position, salary)
        self._skills = skills or []
    
    @property
    def skills(self) -> List[str]:
        return self._skills.copy()
    
    def add_skill(self, skill: str) -> None:
        """添加技能"""
        if skill not in self._skills:
            self._skills.append(skill)
            print(f"Employee {self._name}: Added skill '{skill}'")
    
    def get_total_salary(self) -> float:
        """获取总薪资（个人薪资）"""
        return self._salary
    
    def get_employee_count(self) -> int:
        """获取员工数量（1个）"""
        return 1
    
    def work(self) -> str:
        """工作"""
        return f"IndividualContributor {self._name}: Working on {self._position} tasks using skills: {', '.join(self._skills)}"
    
    def __str__(self) -> str:
        return f"IC({self._name}, {self._position}, {len(self._skills)} skills)"


class Manager(Employee):
    """
    管理者（组合节点）
    """
    
    def __init__(self, name: str, position: str, salary: float, department: str = ""):
        super().__init__(name, position, salary)
        self._department = department
        self._subordinates: List[Employee] = []
    
    @property
    def department(self) -> str:
        return self._department
    
    def add_subordinate(self, employee: Employee) -> None:
        """添加下属"""
        if employee not in self._subordinates:
            self._subordinates.append(employee)
            employee.set_manager(self)
            print(f"Manager {self._name}: Added subordinate {employee.name}")
    
    def remove_subordinate(self, employee: Employee) -> None:
        """移除下属"""
        if employee in self._subordinates:
            self._subordinates.remove(employee)
            employee.set_manager(None)
            print(f"Manager {self._name}: Removed subordinate {employee.name}")
    
    def get_subordinates(self) -> List[Employee]:
        """获取所有下属"""
        return self._subordinates.copy()
    
    def get_direct_reports(self) -> List[Employee]:
        """获取直接下属"""
        return self._subordinates.copy()
    
    def get_all_reports(self) -> List[Employee]:
        """获取所有下属（递归）"""
        all_reports = []
        for subordinate in self._subordinates:
            all_reports.append(subordinate)
            if isinstance(subordinate, Manager):
                all_reports.extend(subordinate.get_all_reports())
        return all_reports
    
    def get_total_salary(self) -> float:
        """获取总薪资（包括所有下属）"""
        total = self._salary
        for subordinate in self._subordinates:
            total += subordinate.get_total_salary()
        return total
    
    def get_employee_count(self) -> int:
        """获取员工数量（包括自己和所有下属）"""
        count = 1  # 自己
        for subordinate in self._subordinates:
            count += subordinate.get_employee_count()
        return count
    
    def work(self) -> str:
        """工作"""
        work_reports = [f"Manager {self._name}: Managing {self._department} department with {len(self._subordinates)} direct reports"]
        
        for subordinate in self._subordinates:
            subordinate_work = subordinate.work()
            indented_work = "  " + subordinate_work.replace("\n", "\n  ")
            work_reports.append(indented_work)
        
        return "\n".join(work_reports)
    
    def get_organization_chart(self, indent: int = 0) -> str:
        """获取组织架构图"""
        prefix = "  " * indent
        chart = [f"{prefix}{self._name} ({self._position}) - ${self._salary:,.0f}"]
        
        for subordinate in self._subordinates:
            if isinstance(subordinate, Manager):
                chart.append(subordinate.get_organization_chart(indent + 1))
            else:
                chart.append(f"{prefix}  {subordinate.name} ({subordinate.position}) - ${subordinate.salary:,.0f}")
        
        return "\n".join(chart)
    
    def find_employee(self, name: str) -> Optional[Employee]:
        """查找员工（递归）"""
        for subordinate in self._subordinates:
            if subordinate.name == name:
                return subordinate
            if isinstance(subordinate, Manager):
                found = subordinate.find_employee(name)
                if found:
                    return found
        return None
    
    def get_department_stats(self) -> Dict[str, Any]:
        """获取部门统计"""
        all_employees = self.get_all_reports()
        positions = defaultdict(int)
        
        for employee in all_employees:
            positions[employee.position] += 1
        
        return {
            "department": self._department,
            "manager": self._name,
            "total_employees": len(all_employees) + 1,  # +1 for manager
            "direct_reports": len(self._subordinates),
            "total_salary_cost": self.get_total_salary(),
            "positions": dict(positions)
        }
    
    def __str__(self) -> str:
        return f"Manager({self._name}, {self._department}, {len(self._subordinates)} reports)"


# ============================================================================
# 4. 图形组合模式
# ============================================================================

class Graphic(ABC):
    """
    图形抽象类
    """
    
    def __init__(self, name: str):
        self._name = name
        self._x = 0.0
        self._y = 0.0
        self._visible = True
    
    @property
    def name(self) -> str:
        return self._name
    
    @property
    def x(self) -> float:
        return self._x
    
    @property
    def y(self) -> float:
        return self._y
    
    @property
    def visible(self) -> bool:
        return self._visible
    
    def move(self, dx: float, dy: float) -> None:
        """移动图形"""
        self._x += dx
        self._y += dy
    
    def set_position(self, x: float, y: float) -> None:
        """设置位置"""
        self._x = x
        self._y = y
    
    def set_visible(self, visible: bool) -> None:
        """设置可见性"""
        self._visible = visible
    
    @abstractmethod
    def draw(self) -> str:
        """绘制图形"""
        pass
    
    @abstractmethod
    def get_bounds(self) -> Dict[str, float]:
        """获取边界"""
        pass
    
    @abstractmethod
    def get_area(self) -> float:
        """获取面积"""
        pass


class Circle(Graphic):
    """
    圆形（叶子节点）
    """
    
    def __init__(self, name: str, radius: float, color: str = "black"):
        super().__init__(name)
        self._radius = radius
        self._color = color
    
    @property
    def radius(self) -> float:
        return self._radius
    
    @property
    def color(self) -> str:
        return self._color
    
    def set_radius(self, radius: float) -> None:
        """设置半径"""
        self._radius = radius
    
    def set_color(self, color: str) -> None:
        """设置颜色"""
        self._color = color
    
    def draw(self) -> str:
        """绘制圆形"""
        if not self._visible:
            return f"Circle {self._name}: Hidden"
        return f"Circle {self._name}: Draw at ({self._x}, {self._y}) radius={self._radius} color={self._color}"
    
    def get_bounds(self) -> Dict[str, float]:
        """获取边界"""
        return {
            "left": self._x - self._radius,
            "right": self._x + self._radius,
            "top": self._y - self._radius,
            "bottom": self._y + self._radius
        }
    
    def get_area(self) -> float:
        """获取面积"""
        return 3.14159 * self._radius * self._radius
    
    def __str__(self) -> str:
        return f"Circle({self._name}, r={self._radius})"


class Rectangle(Graphic):
    """
    矩形（叶子节点）
    """
    
    def __init__(self, name: str, width: float, height: float, color: str = "black"):
        super().__init__(name)
        self._width = width
        self._height = height
        self._color = color
    
    @property
    def width(self) -> float:
        return self._width
    
    @property
    def height(self) -> float:
        return self._height
    
    @property
    def color(self) -> str:
        return self._color
    
    def set_size(self, width: float, height: float) -> None:
        """设置大小"""
        self._width = width
        self._height = height
    
    def set_color(self, color: str) -> None:
        """设置颜色"""
        self._color = color
    
    def draw(self) -> str:
        """绘制矩形"""
        if not self._visible:
            return f"Rectangle {self._name}: Hidden"
        return f"Rectangle {self._name}: Draw at ({self._x}, {self._y}) size={self._width}x{self._height} color={self._color}"
    
    def get_bounds(self) -> Dict[str, float]:
        """获取边界"""
        return {
            "left": self._x,
            "right": self._x + self._width,
            "top": self._y,
            "bottom": self._y + self._height
        }
    
    def get_area(self) -> float:
        """获取面积"""
        return self._width * self._height
    
    def __str__(self) -> str:
        return f"Rectangle({self._name}, {self._width}x{self._height})"


class GraphicGroup(Graphic):
    """
    图形组（组合节点）
    """
    
    def __init__(self, name: str):
        super().__init__(name)
        self._graphics: List[Graphic] = []
    
    def add_graphic(self, graphic: Graphic) -> None:
        """添加图形"""
        self._graphics.append(graphic)
        print(f"GraphicGroup {self._name}: Added {graphic.name}")
    
    def remove_graphic(self, graphic: Graphic) -> None:
        """移除图形"""
        if graphic in self._graphics:
            self._graphics.remove(graphic)
            print(f"GraphicGroup {self._name}: Removed {graphic.name}")
    
    def get_graphics(self) -> List[Graphic]:
        """获取所有图形"""
        return self._graphics.copy()
    
    def move(self, dx: float, dy: float) -> None:
        """移动组中所有图形"""
        super().move(dx, dy)
        for graphic in self._graphics:
            graphic.move(dx, dy)
    
    def set_visible(self, visible: bool) -> None:
        """设置组中所有图形的可见性"""
        super().set_visible(visible)
        for graphic in self._graphics:
            graphic.set_visible(visible)
    
    def draw(self) -> str:
        """绘制组中所有图形"""
        if not self._visible:
            return f"GraphicGroup {self._name}: Hidden"
        
        results = [f"GraphicGroup {self._name}: Drawing group"]
        for graphic in self._graphics:
            graphic_result = graphic.draw()
            indented_result = "  " + graphic_result.replace("\n", "\n  ")
            results.append(indented_result)
        
        return "\n".join(results)
    
    def get_bounds(self) -> Dict[str, float]:
        """获取组的边界（包含所有子图形）"""
        if not self._graphics:
            return {"left": self._x, "right": self._x, "top": self._y, "bottom": self._y}
        
        bounds = [graphic.get_bounds() for graphic in self._graphics]
        
        return {
            "left": min(b["left"] for b in bounds),
            "right": max(b["right"] for b in bounds),
            "top": min(b["top"] for b in bounds),
            "bottom": max(b["bottom"] for b in bounds)
        }
    
    def get_area(self) -> float:
        """获取组的总面积"""
        return sum(graphic.get_area() for graphic in self._graphics)
    
    def get_graphic_count(self) -> int:
        """获取图形数量（递归）"""
        count = 0
        for graphic in self._graphics:
            if isinstance(graphic, GraphicGroup):
                count += graphic.get_graphic_count()
            else:
                count += 1
        return count
    
    def find_graphic(self, name: str) -> Optional[Graphic]:
        """查找图形（递归）"""
        for graphic in self._graphics:
            if graphic.name == name:
                return graphic
            if isinstance(graphic, GraphicGroup):
                found = graphic.find_graphic(name)
                if found:
                    return found
        return None
    
    def __str__(self) -> str:
        return f"GraphicGroup({self._name}, {len(self._graphics)} graphics)"
    
    def __iter__(self) -> Iterator[Graphic]:
        """支持迭代"""
        return iter(self._graphics)


# ============================================================================
# 5. 演示函数
# ============================================================================

def demonstrate_basic_composite():
    """
    演示基本组合模式
    """
    print("\n=== 基本组合模式演示 ===")
    
    # 创建叶子组件
    leaf1 = Leaf("Leaf1", 10)
    leaf2 = Leaf("Leaf2", 20)
    leaf3 = Leaf("Leaf3", 15)
    
    # 创建组合组件
    composite1 = Composite("Composite1")
    composite2 = Composite("Composite2")
    root = Composite("Root")
    
    print("\n=== 构建组合结构 ===")
    
    # 构建树形结构
    composite1.add(leaf1)
    composite1.add(leaf2)
    
    composite2.add(leaf3)
    
    root.add(composite1)
    root.add(composite2)
    
    print("\n=== 执行操作 ===")
    
    # 执行操作
    print("Root operation result:")
    print(root.operation())
    
    print(f"\nRoot total size: {root.get_size()}")
    print(f"Root path: {root.get_path()}")
    print(f"Leaf1 path: {leaf1.get_path()}")
    
    print("\n=== 遍历组合结构 ===")
    
    # 遍历结构
    print("Composite1 children:")
    for child in composite1:
        print(f"  {child}")
    
    # 查找子组件
    found_leaf = composite1.find_child("Leaf1")
    if found_leaf:
        print(f"\nFound: {found_leaf}")
    
    # 移除组件
    print("\n=== 移除组件 ===")
    composite1.remove(leaf1)
    print(f"Composite1 size after removal: {composite1.get_size()}")


def demonstrate_file_system():
    """
    演示文件系统组合模式
    """
    print("\n=== 文件系统组合模式演示 ===")
    
    # 创建根目录
    root = Directory("root")
    
    print("\n=== 创建文件系统结构 ===")
    
    # 创建子目录和文件
    home = root.create_directory("home")
    user = home.create_directory("user")
    documents = user.create_directory("documents")
    
    # 创建文件
    readme = root.create_file("README.md", "# Project README\nThis is a sample project.")
    config = root.create_file("config.json", '{"debug": true, "port": 8080}')
    
    doc1 = documents.create_file("report.txt", "Annual report content here...")
    doc2 = documents.create_file("notes.md", "# Meeting Notes\n- Point 1\n- Point 2")
    
    script = user.create_file("script.py", "#!/usr/bin/env python3\nprint('Hello, World!')")
    
    print("\n=== 文件系统信息 ===")
    
    print(f"Root directory size: {root.get_size()} bytes")
    print(f"Total files in system: {root.get_total_file_count()}")
    
    print("\n=== 目录内容列表 ===")
    print("Root contents:")
    print(root.list_contents(recursive=True))
    
    print("\n=== 文件操作 ===")
    
    # 文件操作
    script.append("\nprint('Python is awesome!')")
    content = script.read()
    print(f"Script content length: {len(content)} characters")
    
    # 查找文件
    print("\n=== 查找文件 ===")
    python_files = root.find_files_by_extension("py")
    print(f"Found {len(python_files)} Python files:")
    for file in python_files:
        print(f"  {file.get_path()}")
    
    md_files = root.find_files_by_extension("md")
    print(f"Found {len(md_files)} Markdown files:")
    for file in md_files:
        print(f"  {file.get_path()} ({file.get_line_count()} lines)")
    
    # 文件信息
    print("\n=== 文件详细信息 ===")
    for file in [readme, script, doc1]:
        info = file.get_info()
        print(f"File: {info['name']}")
        print(f"  Path: {info['path']}")
        print(f"  Size: {info['size']} bytes")
        print(f"  Created: {info['created']}")
        print(f"  Modified: {info['modified']}")
        print()


def demonstrate_organization():
    """
    演示组织结构组合模式
    """
    print("\n=== 组织结构组合模式演示 ===")
    
    print("\n=== 创建组织结构 ===")
    
    # 创建CEO
    ceo = Manager("Alice Johnson", "CEO", 200000, "Executive")
    
    # 创建部门经理
    cto = Manager("Bob Smith", "CTO", 150000, "Technology")
    cfo = Manager("Carol Davis", "CFO", 140000, "Finance")
    hr_manager = Manager("David Wilson", "HR Manager", 120000, "Human Resources")
    
    # 创建团队负责人
    dev_manager = Manager("Eve Brown", "Development Manager", 130000, "Development")
    qa_manager = Manager("Frank Miller", "QA Manager", 110000, "Quality Assurance")
    
    # 创建个人贡献者
    senior_dev1 = IndividualContributor("Grace Lee", "Senior Developer", 100000, ["Python", "JavaScript", "React"])
    senior_dev2 = IndividualContributor("Henry Chen", "Senior Developer", 105000, ["Java", "Spring", "Microservices"])
    junior_dev1 = IndividualContributor("Ivy Wang", "Junior Developer", 70000, ["Python", "Django"])
    junior_dev2 = IndividualContributor("Jack Taylor", "Junior Developer", 65000, ["JavaScript", "Node.js"])
    
    qa_engineer1 = IndividualContributor("Kelly Green", "QA Engineer", 80000, ["Selenium", "TestNG", "API Testing"])
    qa_engineer2 = IndividualContributor("Liam White", "QA Engineer", 75000, ["Cypress", "Jest", "Manual Testing"])
    
    accountant = IndividualContributor("Mia Black", "Accountant", 60000, ["Excel", "QuickBooks", "Financial Analysis"])
    hr_specialist = IndividualContributor("Noah Gray", "HR Specialist", 55000, ["Recruitment", "Employee Relations"])
    
    print("\n=== 构建组织层次 ===")
    
    # 构建组织层次
    ceo.add_subordinate(cto)
    ceo.add_subordinate(cfo)
    ceo.add_subordinate(hr_manager)
    
    cto.add_subordinate(dev_manager)
    cto.add_subordinate(qa_manager)
    
    dev_manager.add_subordinate(senior_dev1)
    dev_manager.add_subordinate(senior_dev2)
    dev_manager.add_subordinate(junior_dev1)
    dev_manager.add_subordinate(junior_dev2)
    
    qa_manager.add_subordinate(qa_engineer1)
    qa_manager.add_subordinate(qa_engineer2)
    
    cfo.add_subordinate(accountant)
    hr_manager.add_subordinate(hr_specialist)
    
    print("\n=== 组织架构图 ===")
    print(ceo.get_organization_chart())
    
    print("\n=== 组织统计 ===")
    print(f"总员工数: {ceo.get_employee_count()}")
    print(f"总薪资成本: ${ceo.get_total_salary():,.2f}")
    
    # 部门统计
    departments = [cto, cfo, hr_manager]
    for dept_manager in departments:
        stats = dept_manager.get_department_stats()
        print(f"\n{stats['department']} 部门统计:")
        print(f"  经理: {stats['manager']}")
        print(f"  总员工数: {stats['total_employees']}")
        print(f"  直接下属: {stats['direct_reports']}")
        print(f"  薪资成本: ${stats['total_salary_cost']:,.2f}")
        print(f"  职位分布: {stats['positions']}")
    
    print("\n=== 工作报告 ===")
    print("Development Manager工作报告:")
    print(dev_manager.work())
    
    print("\n=== 查找员工 ===")
    employee = ceo.find_employee("Grace Lee")
    if employee:
        info = employee.get_info()
        print(f"找到员工: {info['name']}")
        print(f"  职位: {info['position']}")
        print(f"  薪资: ${info['salary']:,.2f}")
        print(f"  层级: {info['level']}")
        print(f"  经理: {info['manager']}")
    
    # 技能统计
    print("\n=== 技能统计 ===")
    all_employees = ceo.get_all_reports()
    skill_count = defaultdict(int)
    
    for emp in all_employees:
        if isinstance(emp, IndividualContributor):
            for skill in emp.skills:
                skill_count[skill] += 1
    
    print("技能分布:")
    for skill, count in sorted(skill_count.items(), key=lambda x: x[1], reverse=True):
        print(f"  {skill}: {count} 人")


def demonstrate_graphics():
    """
    演示图形组合模式
    """
    print("\n=== 图形组合模式演示 ===")
    
    print("\n=== 创建基本图形 ===")
    
    # 创建基本图形
    circle1 = Circle("Circle1", 50, "red")
    circle2 = Circle("Circle2", 30, "blue")
    rect1 = Rectangle("Rect1", 100, 80, "green")
    rect2 = Rectangle("Rect2", 60, 40, "yellow")
    
    # 设置位置
    circle1.set_position(100, 100)
    circle2.set_position(200, 150)
    rect1.set_position(50, 200)
    rect2.set_position(150, 250)
    
    print("\n=== 创建图形组 ===")
    
    # 创建图形组
    group1 = GraphicGroup("Group1")
    group1.add_graphic(circle1)
    group1.add_graphic(rect1)
    
    group2 = GraphicGroup("Group2")
    group2.add_graphic(circle2)
    group2.add_graphic(rect2)
    
    # 创建主组
    main_group = GraphicGroup("MainGroup")
    main_group.add_graphic(group1)
    main_group.add_graphic(group2)
    
    print("\n=== 绘制图形 ===")
    print("绘制主组:")
    print(main_group.draw())
    
    print("\n=== 图形信息 ===")
    print(f"主组图形数量: {main_group.get_graphic_count()}")
    print(f"主组总面积: {main_group.get_area():.2f}")
    
    bounds = main_group.get_bounds()
    print(f"主组边界: left={bounds['left']}, right={bounds['right']}, top={bounds['top']}, bottom={bounds['bottom']}")
    
    print("\n=== 移动图形组 ===")
    print("移动Group1 (50, 30):")
    group1.move(50, 30)
    
    print("\n移动后的边界:")
    bounds = main_group.get_bounds()
    print(f"主组边界: left={bounds['left']}, right={bounds['right']}, top={bounds['top']}, bottom={bounds['bottom']}")
    
    print("\n=== 隐藏图形组 ===")
    print("隐藏Group2:")
    group2.set_visible(False)
    print(main_group.draw())
    
    print("\n=== 查找图形 ===")
    found_circle = main_group.find_graphic("Circle1")
    if found_circle:
        print(f"找到图形: {found_circle}")
        print(f"位置: ({found_circle.x}, {found_circle.y})")
        print(f"面积: {found_circle.get_area():.2f}")
    
    # 单独绘制图形
    print("\n=== 单独绘制图形 ===")
    for graphic in [circle1, rect1, circle2, rect2]:
        print(graphic.draw())


def demonstrate_performance_comparison():
    """
    演示性能对比
    """
    print("\n=== 性能对比演示 ===")
    
    num_components = 1000
    
    print(f"\n=== 测试 {num_components} 个组件的性能 ===")
    
    # 测试平铺结构性能
    print("\n--- 平铺结构性能测试 ---")
    flat_composite = Composite("FlatRoot")
    
    start_time = time.time()
    for i in range(num_components):
        leaf = Leaf(f"Leaf{i}", i + 1)
        flat_composite.add(leaf)
    flat_creation_time = time.time() - start_time
    
    start_time = time.time()
    flat_size = flat_composite.get_size()
    flat_operation_time = time.time() - start_time
    
    print(f"平铺结构创建时间: {flat_creation_time:.3f}秒")
    print(f"平铺结构操作时间: {flat_operation_time:.3f}秒")
    print(f"平铺结构总大小: {flat_size}")
    
    # 测试层次结构性能
    print("\n--- 层次结构性能测试 ---")
    hierarchical_root = Composite("HierarchicalRoot")
    
    start_time = time.time()
    
    # 创建3层结构
    for i in range(10):  # 10个一级组合
        level1_composite = Composite(f"Level1_{i}")
        hierarchical_root.add(level1_composite)
        
        for j in range(10):  # 每个一级组合有10个二级组合
            level2_composite = Composite(f"Level2_{i}_{j}")
            level1_composite.add(level2_composite)
            
            for k in range(10):  # 每个二级组合有10个叶子
                leaf = Leaf(f"Leaf_{i}_{j}_{k}", k + 1)
                level2_composite.add(leaf)
    
    hierarchical_creation_time = time.time() - start_time
    
    start_time = time.time()
    hierarchical_size = hierarchical_root.get_size()
    hierarchical_operation_time = time.time() - start_time
    
    print(f"层次结构创建时间: {hierarchical_creation_time:.3f}秒")
    print(f"层次结构操作时间: {hierarchical_operation_time:.3f}秒")
    print(f"层次结构总大小: {hierarchical_size}")
    
    # 性能对比
    print("\n=== 性能对比结果 ===")
    print(f"创建时间比较: 层次结构比平铺结构{'快' if hierarchical_creation_time < flat_creation_time else '慢'} {abs(hierarchical_creation_time - flat_creation_time):.3f}秒")
    print(f"操作时间比较: 层次结构比平铺结构{'快' if hierarchical_operation_time < flat_operation_time else '慢'} {abs(hierarchical_operation_time - flat_operation_time):.3f}秒")
    
    print("\n=== 组合模式的优势 ===")
    print("""
    组合模式的性能优势:
    1. 统一的接口处理单个对象和组合对象
    2. 简化客户端代码，无需区分叶子和组合
    3. 易于添加新的组件类型
    4. 支持递归操作和遍历
    5. 灵活的树形结构管理
    """)


def demonstrate_java_comparison():
    """
    演示与Java的对比
    """
    print("\n=== Python vs Java 组合模式对比 ===")
    
    print("\n=== Java实现特点 ===")
    print("""
    Java组合模式的实现:
    
    // Java组件接口
    public interface Component {
        void operation();
        void add(Component component);
        void remove(Component component);
        Component getChild(int index);
    }
    
    // Java叶子组件
    public class Leaf implements Component {
        private String name;
        
        public Leaf(String name) {
            this.name = name;
        }
        
        @Override
        public void operation() {
            System.out.println("Leaf " + name + ": operation");
        }
        
        @Override
        public void add(Component component) {
            throw new UnsupportedOperationException("Cannot add to a leaf");
        }
        
        @Override
        public void remove(Component component) {
            throw new UnsupportedOperationException("Cannot remove from a leaf");
        }
        
        @Override
        public Component getChild(int index) {
            throw new UnsupportedOperationException("Leaf has no children");
        }
    }
    
    // Java组合组件
    public class Composite implements Component {
        private List<Component> children = new ArrayList<>();
        private String name;
        
        public Composite(String name) {
            this.name = name;
        }
        
        @Override
        public void operation() {
            System.out.println("Composite " + name + ": operation");
            for (Component child : children) {
                child.operation();
            }
        }
        
        @Override
        public void add(Component component) {
            children.add(component);
        }
        
        @Override
        public void remove(Component component) {
            children.remove(component);
        }
        
        @Override
        public Component getChild(int index) {
            return children.get(index);
        }
    }
    """)
    
    print("\n=== Python实现优势 ===")
    print("""
    Python组合模式的优势:
    
    1. Duck Typing:
       - 不需要显式接口定义
       - 更灵活的类型系统
    
    2. 列表和字典支持:
       - 天然的组合结构支持
       - 内置的迭代和遍历功能
    
    3. 生成器支持:
       - 惰性遍历大型组合结构
       - 内存效率更高
    
    4. 装饰器支持:
       - 可以动态添加组合功能
       - 简化横切关注点
    
    5. 上下文管理器:
       - with语句支持资源管理
       - 自动清理组合结构
    
    6. 弱引用支持:
       - weakref模块避免循环引用
       - 更好的内存管理
    """)
    
    print("\n=== 实际应用场景对比 ===")
    print("""
    应用场景对比:
    
    Java适合:
    - 大型企业应用的层次结构
    - GUI组件树（Swing/JavaFX）
    - 复杂的业务对象组合
    - 需要严格类型检查的系统
    
    Python适合:
    - 文件系统操作
    - 数据结构和算法
    - Web框架的组件系统
    - 配置管理和解析
    - 图形和绘图系统
    - 组织结构管理
    - 快速原型开发
    """)


def main():
    """
    主函数 - 演示所有组合模式实现
    """
    print("组合模式 (Composite Pattern) - Python实现演示")
    print("=" * 60)
    
    # 演示基本组合模式
    demonstrate_basic_composite()
    
    # 演示文件系统组合模式
    demonstrate_file_system()
    
    # 演示组织结构组合模式
    demonstrate_organization()
    
    # 演示图形组合模式
    demonstrate_graphics()
    
    # 演示性能对比
    demonstrate_performance_comparison()
    
    # 演示Java对比
    demonstrate_java_comparison()
    
    print("\n=== 总结 ===")
    print("""
    组合模式的核心思想:
    1. 将对象组合成树形结构以表示"部分-整体"的层次结构
    2. 使得用户对单个对象和组合对象的使用具有一致性
    3. 简化客户端代码，无需区分叶子和组合对象
    
    Python实现特点:
    1. 利用Duck Typing实现灵活的组合结构
    2. 使用列表和字典提供天然的组合支持
    3. 支持生成器和迭代器进行高效遍历
    4. 装饰器可以动态添加组合功能
    5. 上下文管理器支持资源管理
    
    适用场景:
    1. 文件系统和目录结构
    2. 组织架构和层次管理
    3. GUI组件树和图形系统
    4. 菜单和导航结构
    5. 表达式和语法树
    6. 配置管理和解析
    """)


if __name__ == "__main__":
    main()